/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.webos.java.rssreader;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import java.io.InputStreamReader;
import java.net.URL;
import org.json.JSONObject;
import org.webos.java.base.Dialog;
import org.webos.java.base.DialogType;
import org.webos.java.base.NetworkManager;
import org.webos.java.base.RemoteMessage;
import org.webos.java.base.SystemManager;
import org.webos.java.root.Log;
import org.webos.java.rssreader.FoldersFeeds.FeedItem;
import org.xml.sax.InputSource;

/**
 *
 * @author Kostya
 */

@DialogType(jsClass="rssreader.FeedEditor")
public class FeedEditor extends Dialog<RSSReader>{

    boolean newFeed = false;
    FeedItem feedItem = null;

    FeedEditor(RSSReader aRSSReader, boolean aNewFeed, FeedItem aItem) {
        super(aRSSReader);
        newFeed = aNewFeed;
        feedItem = aItem;
        getData().putOpt("name", aItem.name);
        getData().putOpt("url", aItem.url);
        getData().putOpt("newFeed", newFeed);
        show();
    }

    @RemoteMessage
    public JSONObject okClick(JSONObject aObject){
        try {
            feedItem.name = aObject.optString("name", "");
            if(newFeed)
                feedItem.url = aObject.optString("url", "");
            if("".equals(feedItem.name))
                return NetworkManager.getErrorObject(1205, "Name can't be empty");
            if("".equals(feedItem.url) && newFeed)
                return NetworkManager.getErrorObject(1206, "URL can't be empty");
            if(!getApplication().foldersFeeds.saveFeed(newFeed, feedItem))
                return NetworkManager.getErrorObject(1207, "Can't save feed in DB");
            closeDialog(aObject);
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return null;
    }

    @RemoteMessage
    public JSONObject fetchFeed(JSONObject aObject){
        try {
            URL url = new URL(aObject.optString("url", ""));
            SyndFeedInput input = new SyndFeedInput();
            SyndFeed feed = input.build(new InputSource(url.openStream()));
            aObject.putOpt("name", feed.getTitle());
            return aObject;
        } catch (Throwable t) {
            Log.error(this, "Exception thrown: " + t.getMessage());
            t.printStackTrace();
        }
        return NetworkManager.getErrorObject(1208, "Can't fetch feed contents. Network error");
    }

}
